package com.artconcurrency.chapter4;

/**
 * @ClassName com.artconcurrency.chapter4
 * Description:
 * NEW和TERMINATED对于中断操作几乎是屏蔽的，
 * RUNNABLE和BLOCKED类似，对于中断操作只是设置中断标志位并没有强制终止线程，对于线程的终止权利依然在程序手中。
 * WAITING/TIMED_WAITING状态下的线程对于中断操作是敏感的，他们会抛出异常并清空中断标志位。
 * <p>
 *     运行结果：
sleepthread interrupted is false
    java.lang.InterruptedException: sleep interrupted
    at java.lang.Thread.sleep(Native Method)
    at java.lang.Thread.sleep(Thread.java:340)
    at java.util.concurrent.TimeUnit.sleep(TimeUnit.java:386)
    at com.artconcurrency.chapter4.SleepUtils.second(SleepUtils.java:18)
    at com.artconcurrency.chapter4.SleepRunner.run(Interrupted.java:45)
    at java.lang.Thread.run(Thread.java:748)
busyThread interrupted is true
 * </p>
 * @Author tree
 * @Date 2019-05-01 20:50
 * @Version 1.0
 */
public class Interrupted {

    public static void main(String[] args) {
        //sleep 线程不断睡眠
        Thread sleepThread = new Thread(new SleepRunner(),"sleepthread");
        sleepThread.setDaemon(true);
        //busy线程不断运行
        Thread busyThread = new Thread(new BusyRunner(),"busyThread ");
        busyThread.setDaemon(true);

        sleepThread.start();
        busyThread.start();
        //休眠5s，让busyThread与sleepThread充分运行
        SleepUtils.second(5);

        //中断线程
        sleepThread.interrupt();
        System.out.println("sleepthread interrupted is "+sleepThread.isInterrupted());
        SleepUtils.second(5);
        busyThread.interrupt();
        System.out.println("busyThread interrupted is "+busyThread.isInterrupted());

        //休息s，防止busyThread与sleepThread立马退出
        SleepUtils.second(2);
    }
}

class SleepRunner implements Runnable{
    @Override
    public void run() {
        while (true){
            SleepUtils.second(10);
        }
    }
}
class BusyRunner implements Runnable{
    @Override
    public void run() {
        while (true){}
    }
}
